<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="3" :lg="4" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="4" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, commonIndex) in approveStatus" :key="commonIndex" :label="item" :value="commonIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="3" :md="5" :sm="6" hidden>
                    <el-form-item>
                      <div class="search_label">负责人</div>
                      <v-select v-model="query.admin_id" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="3" :lg="2" :md="5" :sm="6">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox" hidden>
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="设备组导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="marginLeft20" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div v-if="isAdmin" class="buttonBox">
                <el-button type="primary" icon="el-icon-set-up" size="mini" @click="orders">执行</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-row>
        <el-col :span="24">
          <el-table v-loading="loading" :data="approveList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" :height="tableMaxHeight" @selection-change="selectionHandler">
            <el-table-column type="index" width="50" label="序号" align="center" />
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="coding" label="编号" min-width="25%" align="center" />
            <el-table-column prop="name" label="名称" min-width="25%" align="center" />
            <el-table-column prop="status" label="状态" min-width="25%" align="center" :formatter="statusFormat" />
            <el-table-column v-if="listHandle" fixed="right" label="操作" min-width="25%" align="center">
              <template scope="scope">
                <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="confirmDel(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import API from '@/api/project/approve'
import { approveStatus } from '@/utils/options'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
import VSelect from '@/components/select'
import { mapGetters } from 'vuex'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getApproveStatusFormat', 'getScope'],
  components: {
    VSelect
  },
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '名称', '成本中心', '状态', '类型', '负责人', '电话'],
      loading: false,
      total: 0,
      query: { page: 1, limit: 15 },
      approveList: [],
      selection: [],
      isAdmin: false,
      approveStatus
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ]),
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
    const scope = this.getScope(this.userId)
    if (scope === 1 || scope === 2) {
      this.isAdmin = true
    }
  },
  methods: {
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    index() {
      this.loading = true
      API.approveList(this.query).then(response => {
        this.total = response.data.total
        this.approveList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.groupList(this.query).then(response => {
          this.selection = response.data.data
        }).finally(() => {
          this.thisExport()
          this.loading = false
        })
      } else {
        this.thisExport()
      }
    },
    thisExport() {
      this.selection.forEach((item) => {
        if (item.status === 0) {
          item.statusOut = '启用'
        } else if (item.status === 1) {
          item.statusOut = '停用'
        }

        if (item.type === 0) {
          item.typeOut = '设备'
        } else if (item.type === 1) {
          item.typeOut = '工装'
        }
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'name': '名称',
        'cost.coding': '成本中心',
        'statusOut': '状态',
        'typeOut': '类型',
        'admin.name': '负责人',
        'admin.phone': '电话'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['equipmentGroup'],
          Sheets: {
            'equipmentGroup': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '设备组数据.xlsx')
      }
    },
    remove() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      this.delOne(API, id, false)
    },
    addHandler() {
      this.goUrl('/project/approve/approve_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/project/approve/approve_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    orders() {
      API.orders().then(res => {
        if (res.code === 200) {
          this.$message({
            message: '恭喜你，执行成功',
            type: 'success'
          })
        }
      })
    },
    statusFormat(row) {
      if (row.status === 0) {
        return this.$createElement('div', { 'style': { 'color': 'gray' }}, '待审')
      } else if (row.status === 1) {
        return this.$createElement('div', { 'style': { 'color': 'green' }}, '通过')
      }
    },
    workbook(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excel(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，导入成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    workbooks(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excels(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，导入成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    }
  }
}
</script>
